package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryList() {
        String cachekey = "cache:shopType:list";
        // 从redis中查询缓存
        String cacheString = stringRedisTemplate.opsForValue().get(cachekey);
        // 如果有，直接返回
        if(StrUtil.isNotBlank(cacheString)){
            List<ShopType> shopTypes = JSONUtil.toList(cacheString, ShopType.class);
            return Result.ok(shopTypes);
        }
        // 如果为空，查询数据库
        List<ShopType> shopTypes = query().orderByAsc("sort").list();
        // 数据库没有，直接返回
        if(shopTypes==null|| shopTypes.isEmpty()){
            return Result.fail("List<ShopType>不存在");
        }
        // 数据库有，将数据存于redis中
        stringRedisTemplate.opsForValue().set(cachekey,JSONUtil.toJsonStr(shopTypes));
        return Result.ok(shopTypes);
    }
}
